var fs = require("fs");
var ImageToStruct = require("./utils/image-to-struct.js");
var JSMin = require("./utils/js-min.js");
var KeepLine = require("./utils/keep-line.js");
var Promise = require("bluebird");

var Js2Image = function (jsCode, imagePath, options, callback) {
    ImageToStruct(imagePath, options).then(function (struct) {
        JSMin(jsCode).then(function (code) {
            //fs.writeFileSync(jsPath.replace(".js",".min.js"),code,'utf-8')
            //提取不换行的字符串
            var hold_code = KeepLine.pickFromCode(code);
            //分离代码，以可分割单位拆分成数组。
            var lines = hold_code.replace(/([^a-zA-Z_0-9=!|&$])/g, "\n$1\n").split("\n");
            //把分离后的代码里的占位符替换回代码。
            KeepLine.findBack(lines);
            var result = "";
            while(lines.length > 0) {
                //循环往struct里填充代码
                struct.forEach(function (s) {
                    var chars_arr = s.replace(/ +/g, " ");//一行有多组分离的*****
                    var r = s;
                    chars_arr.split(/ +/).forEach(function (chars) {
                        if(chars.length == 0) {
                            return;
                        }
                        var char_count = chars.length;
                        //从lines里取出char_count数量的代码来填充,不一定精准,要确保断行正确
                        var l = pickFromLines(lines, char_count);

                        r = r.replace(chars, function () {
                            return l;
                        })
                    })
                    result += r + "\n"
                })

            }
            //result就是最终的代码
            callback(null, result);
        }).catch(function (e) {
            callback(e);
        });
    })


}

module.exports = {
    /**
     * 从源文件读取，然后写到目标文件里。
     * @param jsPath
     * @param imagePath
     * @param outputPath
     * @param options
     * @param callback
     */
    writeToFile: function (jsPath, imagePath, outputPath, options) {
        var jsCode = fs.readFileSync(jsPath);
        return new Promise(function (resolve, reject) {
            Js2Image(jsCode.toString(), imagePath, options, function (e, code) {

                code = "/* generated by https://github.com/xinyu198736/js2image */ \n\n" + code;
                fs.writeFileSync(outputPath, code, 'utf-8');
                if(e) {
                    reject(e);
                } else {
                    resolve(code);
                }

            })
        })
    },
    /**
     * 从源代码字符串开始，直接返回一个处理后的code
     * @param jsCode
     * @param imagePath
     * @param options
     * @returns {bluebird|exports|module.exports}
     */
    getCode: function (jsCode, imagePath, options) {
        return new Promise(function (resolve, reject) {
            Js2Image(jsCode, imagePath, options, function (e, code) {
                if(e) {
                    reject(e);
                } else {
                    resolve(code);
                }
            })
        })

    }
};
/**
 * 从lines数组里顺序取字符来填充到指定的长度，不一定精确。
 * @param count
 * @returns {string}
 */
function pickFromLines (lines, count) {

    var t = "";
    var has_pick_count = 0; //取了多少次
    var now_length = 0; //当前填充的长度
    for(var i = 0; i < lines.length; i++) {
        var l = lines[i];
        now_length += l.length;
        has_pick_count++;
        if(now_length > count) {
            if(now_length - count > 3 && has_pick_count > 1) {
                //如果长度超长太多，去掉最后一个填充进来的字符串。
                has_pick_count--;
            }
            break;
        }
    }
    for(var i = 0; i < has_pick_count; i++) {
        var s = lines.shift();
        t += s;
    }
    return t;
}